import socket
from Netlayer.ipTools import *
import time
import select

class DeviceListener:
    def __init__(self,ip,mask):
        #初始化socket TCP Mode
        self.socketTcp = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.ip = ip
        self.mask = mask
        self.clientList=[]

    def scan(self):
        ip = self.ip
        mask = self.mask
        #初始化socket UDP Mode 用于广播寻找客户d
        socketUDP = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        socketUDP.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
        socketUDP.setblocking(0)
        broadcastAddr = generateBroadcastByIPAndMask(ip,mask)
        socketUDP.sendto("broadcast".encode("utf-8"),(broadcastAddr,9999))
        start = time.time()
        while True:
            end = time.time()
            if end - start > 2:
                break
            print(end-start)
            ready = select.select([socketUDP], [], [], 1)
            data=b""
            if ready[0]:
                data ,addr = socketUDP.recvfrom(1024)
            # print(data)
            if data.decode("utf-8").split(":")[0] == "here":
                name = data.decode("utf-8").split(":")[1]
                self.clientList.append([name,addr])
                # print(self.clientList)
        # print(self.clientList)
        return self.clientList

if __name__ == "__main__":
    mySocket = DeviceListener("10.23.178.164","255.255.255.0")
    mySocket.scan()